package com.lemo.smart.proxy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;

/**
 * Created by 罗选通 on 2017/12/25.
 */
public abstract class AspectProxy implements Proxy {
  private static final Logger logger = LoggerFactory.getLogger(AspectProxy.class);

  /**
   * 执行链式代理
   */
  @Override
  public Object doProxy(ProxyChain proxyChain) throws Throwable {
    Object result = null;

    Class<?> targetClass = proxyChain.getTargetClass();
    Method targetMethod = proxyChain.getTargetMethod();
    Object[] methodParams = proxyChain.getMethodParams();

    begin();

    try {
      if (intercept(targetClass, targetMethod, methodParams)) {
        before(targetClass, targetMethod, methodParams);
        result = proxyChain.doProxyChain();
        after(targetClass, targetMethod, methodParams);
      } else {
        result = proxyChain.doProxyChain();
      }
    } catch (Exception e) {
      logger.error("proxy failure", e);
      error(targetClass, targetMethod, methodParams, e);
      throw e;
    }
    return result;
  }

  public void error(Class<?> targetClass, Method targetMethod, Object[] methodParams, Exception e) {
  }

  public void after(Class<?> targetClass, Method targetMethod, Object[] methodParams) {
  }

  public void before(Class<?> targetClass, Method targetMethod, Object[] methodParams) {

  }

  public boolean intercept(Class<?> targetClass, Method targetMethod, Object[] methodParams) {
    return true;
  }

  public void begin() {
  }


}
